package com.sgcc.activiti.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.sgcc.activiti.domain.PendingLeaderboards;
import com.sgcc.activiti.domain.vo.DateSlot;
import com.sgcc.common.core.utils.DateUtils;
import com.sgcc.common.security.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sgcc.activiti.mapper.OAnomalyStatMapper;
import com.sgcc.activiti.domain.OAnomalyStat;
import com.sgcc.activiti.service.IOAnomalyStatService;

/**
 * 看板统计 Service业务层处理
 *
 * @author sgcc
 * @date 2021-04-07
 */
@Service
public class OAnomalyStatServiceImpl implements IOAnomalyStatService {
    @Autowired
    private OAnomalyStatMapper oAnomalyStatMapper;
    @Autowired
    private TokenService tokenService;

    /**
     * 查询看板统计
     *
     * @param statDate 看板统计 ID
     * @return 看板统计
     */
    @Override
    public OAnomalyStat selectOAnomalyStatById(String statDate) {
        return oAnomalyStatMapper.selectOAnomalyStatById(statDate);
    }

    /**
     * 查询看板统计 列表
     *
     * @param oAnomalyStat 看板统计
     * @return 看板统计
     */
    @Override
    public List<OAnomalyStat> selectOAnomalyStatList(OAnomalyStat oAnomalyStat) {
        return oAnomalyStatMapper.selectOAnomalyStatList(oAnomalyStat);
    }

    /**
     * 新增看板统计
     *
     * @param oAnomalyStat 看板统计
     * @return 结果
     */
    @Override
    public int insertOAnomalyStat(OAnomalyStat oAnomalyStat) {
        return oAnomalyStatMapper.insertOAnomalyStat(oAnomalyStat);
    }

    /**
     * 修改看板统计
     *
     * @param oAnomalyStat 看板统计
     * @return 结果
     */
    @Override
    public int updateOAnomalyStat(OAnomalyStat oAnomalyStat) {
        return oAnomalyStatMapper.updateOAnomalyStat(oAnomalyStat);
    }

    /**
     * 批量删除看板统计
     *
     * @param statDates 需要删除的看板统计 ID
     * @return 结果
     */
    @Override
    public int deleteOAnomalyStatByIds(String[] statDates) {
        return oAnomalyStatMapper.deleteOAnomalyStatByIds(statDates);
    }

    /**
     * 删除看板统计 信息
     *
     * @param statDate 看板统计 ID
     * @return 结果
     */
    @Override
    public int deleteOAnomalyStatById(String statDate) {
        return oAnomalyStatMapper.deleteOAnomalyStatById(statDate);
    }


    @Override
    public Map getMonitorCount(PendingLeaderboards pendingLeaderboards) {
        return oAnomalyStatMapper.getMonitorCount(pendingLeaderboards);
    }

    @Override
    public List<HashMap<String, String>> getSystemMonitoring() {
        return oAnomalyStatMapper.getSystemMonitoring();
    }

    @Override
    public List<HashMap<String, String>> monitoringType() {
        return oAnomalyStatMapper.getMonitoringType();
    }


    /**
     * 获取待处理异常数
     *
     * @return
     */
    @Override
    public List<HashMap<String, String>> pendingException(PendingLeaderboards pendingLeaderboards) {
        HashMap<String, String> mapList = oAnomalyStatMapper.getPendingException(pendingLeaderboards);
        List<HashMap<String, String>> hashMaps = new ArrayList<>();
        HashMap<String, String> map1 = new HashMap<>();
        map1.put("name", "待处理数");
        map1.put("value", mapList.get("1"));

        HashMap<String, String> map2 = new HashMap<>();
        map2.put("name", "超3小时");
        map2.put("value", mapList.get("2"));


        HashMap<String, String> map3 = new HashMap<>();
        map3.put("name", "超6小时");
        map3.put("value", mapList.get("3"));


        HashMap<String, String> map4 = new HashMap<>();
        map4.put("name", "超12小时");
        map4.put("value", mapList.get("4"));
        hashMaps.add(map1);
        hashMaps.add(map2);
        hashMaps.add(map3);
        hashMaps.add(map4);
        return hashMaps;
    }


    @Override
    public List<PendingLeaderboards> pendingLeaderboards(PendingLeaderboards pendingLeaderboards) {
        return oAnomalyStatMapper.getPendingLeaderboards(pendingLeaderboards);
    }


    @Override
    public List<HashMap<String, String>> getPendingSystem(String monsyscode, String monsystype) {
        String[] monsysType = monsystype.split(",");
        String[] monsysCode = null;
        if (StringUtils.isNotBlank(monsyscode)) {
            monsysCode = monsyscode.split(",");
        }

        List<HashMap<String, String>> ss = oAnomalyStatMapper.getPendingSystem(monsysCode, monsysType);
        return ss;
    }

    @Override
    public List<HashMap<String, Object>> getPendingSystemforhistogram(String monsyscodes, String monsystype, String alltime, String dt) throws ParseException {
        String companyId = tokenService.getLoginUser().getSysUser().getDeptId(); //获取当前登录人单位id
        String[] monsysCode = null;
        if (StringUtils.isNotBlank(monsyscodes)) {
            monsysCode = monsyscodes.split(",");
        }
        String[] monType = monsystype.split(",");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        Calendar calendar = new GregorianCalendar();

        calendar.setTime(new Date());
        List<HashMap<String, Object>> ss = new ArrayList<HashMap<String, Object>>();
        if ("".equals(alltime) || StringUtils.isBlank(alltime) || "null".equals(alltime)) {
            String bdate = df.format(new Date());
            ss = oAnomalyStatMapper.getPendingSystemforhistogram(monsysCode, monType, bdate, null, dt,companyId);
        } else {
            String[] time = alltime.split(",");
            Date date1 = df.parse(time[0]);
            Date date2;
            if (time[1] != null && !time[1].equals("null") && StringUtils.isNotBlank(time[1])) {
                date2 = df.parse(time[1]);
            } else {
                date2 = new Date();
            }
            String bdate = df.format(date1);
            String edate = df.format(date2);
            ss = oAnomalyStatMapper.getPendingSystemforhistogram(monsysCode, monType, bdate, edate, dt,companyId);
        }
        Long total = 0L;
        for (HashMap<String, Object> s : ss) {
            total+=Long.valueOf(s.get("infonums").toString());
        }
        for (HashMap<String, Object> s : ss) {
            s.put("allinfonums",total);
        }

        return ss;
    }

    @Override
    public List<HashMap<String, Object>> getMonTypePercentage(String monsystype) {
        String[] dd = null;
        if (StringUtils.isNotBlank(monsystype)) {
            dd = monsystype.split(",");
        }
        List<HashMap<String, Object>> ss = oAnomalyStatMapper.getMonTypePercentage(dd);
        System.out.println(ss);
        return ss;
    }

    @Override
    public List<HashMap<String, String>> getSysAbnormalRank(DateSlot dateSlot) {
        List<HashMap<String, String>> list = oAnomalyStatMapper.getSysAbnormalRank(dateSlot);
        return list;
    }

    @Override
    public List<HashMap<String, String>> getSysAbnormalTrend(String type, DateSlot dateSlot) {
        if (StringUtils.isNotBlank(type) && "01".equals(type)) {
            //查看今日，监控异常趋势
            List<HashMap<String, String>> list = oAnomalyStatMapper.getTodayTrend();
            return list;
        } else if (StringUtils.isNotBlank(type) && "02".equals(type)) {
            //查看本周，监控异常趋势
            List<HashMap<String, String>> list = new ArrayList<>();
            /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            // 今天是一周中的第几天
            int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

            if (c.getFirstDayOfWeek() == Calendar.SUNDAY) {
                c.add(Calendar.DAY_OF_MONTH, 1);
            }
            // 计算一周开始的日期
            c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);*/

            for (int i = 1; i <= 7; i++) {
                // 获取前几天的时间
                String datestr = DateUtils.getPastDate(i);
                /*c.add(Calendar.DAY_OF_MONTH, 1);
                String datestr = sdf.format(c.getTime());*/
                int totals = oAnomalyStatMapper.getTrendByDate(datestr);
                HashMap<String, String> map =new HashMap<>();
                map.put("times",datestr);
                map.put("totalnum",totals+"");
                list.add(map);
            }

            return list;
        }
        else if (StringUtils.isNotBlank(type)&&"03".equals(type)) {
            //查看本月，监控异常趋势
            List<HashMap<String, String>> list = new ArrayList<>();
            Calendar c = Calendar.getInstance();
            c.set(Calendar.DATE, 1);
            int month = c.get(Calendar.MONTH);
            while(c.get(Calendar.MONTH) == month){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String datestr = sdf.format(c.getTime());
                int totals = oAnomalyStatMapper.getTrendByDate(datestr);
                HashMap<String, String> map =new HashMap<>();
                map.put("times",datestr);
                map.put("totalnum",totals+"");
                c.add(Calendar.DATE, 1);
                list.add(map);
            }
            return list;
        }else if (StringUtils.isNotBlank(type)&&"04".equals(type)) {
            //查看本年，监控异常趋势
            List<HashMap<String, String>> list = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.MONTH, 0);
            int month = cal.get(Calendar.YEAR);
            while(cal.get(Calendar.YEAR) == month){
                String datestr = sdf.format(cal.getTime());
                cal.add(Calendar.MONTH, 1);
                int totals = oAnomalyStatMapper.getYearTrend(datestr+"-01");
                HashMap<String, String> map =new HashMap<>();
                map.put("times",datestr);
                map.put("totalnum",totals+"");
                list.add(map);
            }
            return list;
        }else if (StringUtils.isNotBlank(type)&&"05".equals(type)) {
            //查看时间范围，监控异常趋势
            try {

            List<HashMap<String, String>> list = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date startDate = dateSlot.getStarttime();
            Date endDate = dateSlot.getEndtime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            while(!calendar.getTime().after(endDate)){
//                calendar.add(Calendar.DAY_OF_MONTH, 1);
                String datestr = sdf.format(calendar.getTime());
                int totals = oAnomalyStatMapper.getTrendByDate(datestr);
                HashMap<String, String> map =new HashMap<>();
                map.put("times",datestr);
                map.put("totalnum",totals+"");
                calendar.add(Calendar.DATE, 1);
                list.add(map);
            }
            return list;
            }catch (Exception e){
                System.out.println(e.toString());
            }
        }
        return null;
    }


    @Override
    public void updateOAnomalyStatTask() {
        //获取该时段的整点时间
//        Date date= DateUtil.addHours(new Date(), 15);
//        String s = DateUtils.formatDate(date1, "yyyy-MM-dd HH:mm:ss");
        String date = DateUtils.getDatetime();

        //查看该时段异常数据
        List<HashMap> result = oAnomalyStatMapper.getHourAbnormal(date);

        //向异常统计表中，插入数据
        if (result.size()>0) {
            oAnomalyStatMapper.insertOAbnormalStat(date);
        }

        //判断如果时间为零点，要统计一天的数据
        if ("00".equals(date.substring(11, 13))) {
            //统计前一天的数据
            List<HashMap> lastday = oAnomalyStatMapper.getLastDayAbnormal(date);

            //插入统计今天一天的数据
            if (lastday.size()>0) {
                oAnomalyStatMapper.insertDayOAbnormal(date);
            }
        }
    }
}
